<script setup lang="ts">
  import { getNamesValues } from '@/utils/nameValues'
  import { onLoad } from '@dcloudio/uni-app'
  import { ref, onMounted, watch } from 'vue'
  import sign from '@/components/sign.vue'
  import { saveClSign } from '@/services/home'
  import { getStoreList } from '@/services/inspection'
  import func from '@/utils/func'
  import { useMemberStore } from '@/stores'
  import { reginDetail } from '@/utils/location'

  interface LocationData {
    latitude : number
    longitude : number
  }
  const userInfo : any = useMemberStore().getUserInfo()//用户信息
  const emit = defineEmits(['refresh', 'close'])
  //界面传参数

  //加载中
  const loading = ref(false)
  const showPicker = ref(false)
  const data = ref({})
  const ruleForm = ref(null)
  let canCheckin = ref(false)
  let isWithinRange = ref(true)
  let hasLocationPermission = ref(true)
  let showRipple = ref(false)
  // 用户当前位置信息
  const userLocation = ref<LocationData>({
    latitude: 0,
    longitude: 0,
  })
  //当前选中的 门店
  let storeData : any = null

  // 当前距离
  const distance = ref(9999)
  const distanceStr = ref('')
  const checkinAddress = ref('')


  // 获取当前位置
  function getLocation() {
    uni.getLocation({
      type: 'gcj02',
      // isHighAccuracy: true,
      success: (res) => {
        userLocation.value = {
          latitude: res.latitude,
          longitude: res.longitude,
        }
        console.log('当前位置的经度：', res.longitude)
        console.log('当前位置的纬度：', res.latitude)
        console.log('当前位置：', res)
        hasLocationPermission.value = false
        //计算位置距离
        // calculateDistance()
        // 获取当前位置的中文描述
        reginDetail(res.longitude, res.latitude).then((res:any) => {
          console.log(res)
          checkinAddress.value = res.address
          areaName = res.city
        })
      },
      fail: (err) => {
        console.error('获取位置失败：', err)
        hasLocationPermission.value = true
        canCheckin.value = false
        uni.showToast({ title: '获取位置失败', icon: 'none' })
      },
    })
  }



  function calculate(lat1 : any, lon1 : any, lat2 : any, lon2 : any) {
    const toRadians = (angle : any) => angle * (Math.PI / 180);

    const R = 6371; // 地球半径（公里）
    const dLat = toRadians(lat2 - lat1);
    const dLon = toRadians(lon2 - lon1);

    const a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(toRadians(lat1)) *
      Math.cos(toRadians(lat2)) *
      Math.sin(dLon / 2) *
      Math.sin(dLon / 2);

    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = R * c; // 距离（公里）

    return distance;
  }
  // 计算两点之间的距离
  function calculateDistance(store : any) {
    if (!userLocation.value) {
      uni.showToast({
        title: '获取用户位置失败',
        icon: 'none',
      })
      hasLocationPermission.value = false
      return
    }
    if (!store.latitude || !store.longitude) {
      uni.showToast({
        title: '门店位置信息异常',
        icon: 'none',
      })
      canCheckin.value = false
      return
    }
    const lat1 = store.latitude
    const lng1 = store.longitude
    const lat2 = userLocation.value.latitude
    const lng2 = userLocation.value.longitude
    console.log('用户经度', lng2)
    console.log('用户纬度', lat2)
    distance.value = calculate(lat1, lng1, lat2, lng2)


    console.log(distance.value, '距离多少米')
    if (distance.value < 500) {
      canCheckin.value = true
      isWithinRange.value = true
    } else {
      isWithinRange.value = false
      canCheckin.value = false
    }
    distanceStr.value = `当前距离服务地址：${distance.value}米`

    console.log(distanceStr.value)
  }

  // 弧度计算
  function toRadians(degrees : number) {
    return (degrees * Math.PI) / 180.0
  }
  function storeChange(store : any) {
    //切换门店
    canCheckin.value = true
    isWithinRange.value = true

    console.log(store)
    storeData = store
    //计算距离
    calculateDistance(store)
  }
  //看看这个算的准不准 两点距离是否计算正确 不对的话请帮忙修改
  // 立即签到
  async function goSignIn() {
    console.log(canCheckin.value)
    if (!storeData) {
      uni.showToast({
        title: '请先选门店L'
      })
    }
    if (!canCheckin.value) {
      return
    }
    loading.value = true
    const signinTime = func.getBeijingTimeISOString()
    try {
      await saveClSign({
        shopCode: storeData.value,
        shopName: storeData.text,
        cityCode: storeData.cityCode,
        areaCode: storeData.areaCode,
        provinceCode: storeData.provinceCode,
        provinceName: storeData.provinceName,
        cityName: storeData.cityName,
        areaName: storeData.areaName,
        loc: checkinAddress.value,
        userCode: userInfo.userCode,
        signinTime
      })
      uni.showToast({ icon: 'none', title: '签到成功', duration: 2000 })
      // 触发刷新
      emit('refresh')
    } catch (error) {
      console.error(error)
    } finally {
      loading.value = false
    }
  }

  // 页面加载
  onLoad(() => {
    getLocation()

  })
  onMounted(() => {

  })
</script>

<template>
  <view class="page">

    <sign class="full-height" :canCheckin="canCheckin" :hasLocationPermission="hasLocationPermission"
      :checkinAddress="checkinAddress" :isWithinRange="isWithinRange" :showRipple="showRipple"
      @storeChange="storeChange" @checkin="goSignIn" @close="emit('close')" />


  </view>
</template>

<style lang="scss">
  .full-height {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .page {
    .scrollV {
      display: flex;
      flex-direction: column;
      height: 100%;
      width: 100%;
    }

    .content {
      display: flex;
      flex-direction: column;
      height: 100%;
      width: 100%;
    }

    .mapV-box {
      flex: 1;
      margin-top: 14px;
    }

    .sign-box {
      width: 80%;
      margin-top: 14px;
    }

    .mapV {
      width: 100%;
      height: 100%;
    }

    .title {
      padding: 20rpx;
      font-size: 32upx;
      font-weight: bold;
      text-align: center;
    }

    .tips {
      padding: 20rpx;
      font-size: 28upx;
      color: gray;
      text-align: center;
    }

    .inputView {
      flex-direction: row;
      display: flex;
      height: auto;
      justify-content: center;
      align-items: center;
      margin-left: 13px;
      width: calc(100vw - 30px);
      padding: 2px 0px;
      font-size: 13px;
      color: gray;
    }

    .nosign {}

    .btnview {
      display: flex;
      background-color: #ff731e;
      justify-content: center;
      align-items: center;
      color: #ffffff;
      width: 100%;
      height: 50px;
      margin-top: 20px;
    }
  }

  .footer-button {
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: #fff;
    padding: 10rpx;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);

    .button-grop {
      display: flex;
      flex-flow: row wrap;
      margin: 5rpx;

      .button-operate {
        margin-right: 10rpx;
      }
    }
  }
</style>
